<template>
  <div class="sale-return-update-page">
    <el-page-header
      content="编辑销售退货"
      @back="handleBack"
      class="page-header"
    />

    <el-form
      ref="formRef"
      :model="form"
      :rules="formRules"
      label-width="100px"
      class="returns-form"
    >
      <el-card shadow="never" class="card-section">
        <template #header>
          <div class="card-header">
            <span>基础信息</span>
            <el-tag v-if="form.saleReturnsStatusText" size="small">
              {{ form.saleReturnsStatusText }}
            </el-tag>
          </div>
        </template>

        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="销售退货单号" prop="saleReturnsNo">
              <el-input
                v-model="form.saleReturnsNo"
                placeholder="自动获取系统编号"
                readonly
                class="readonly-input"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="退货日期" prop="saleReturnsDate">
              <el-date-picker
                v-model="form.saleReturnsDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择退货日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="销售单号" prop="salesOrderNo">
              <el-input
                v-model="form.salesOrderNo"
                placeholder="请选择"
                readonly
                @click="openSalesOrderDialog"
              >
                <template #append>
                  <el-button text type="primary" @click.stop="openSalesOrderDialog">
                    选择
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="6">
            <el-form-item label="客户名称" prop="customerName">
              <el-input
                v-model="form.customerName"
                placeholder="请选择销售单后自动带出"
                readonly
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系人">
              <el-input
                v-model="form.contactName"
                placeholder="请选择销售单后自动带出"
                readonly
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系方式">
              <el-input
                v-model="form.contactPhone"
                placeholder="请选择销售单后自动带出"
                readonly
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="销售部门">
              <el-input
                v-model="form.salesDepartment"
                placeholder="请选择销售单后自动带出"
                readonly
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="6">
            <el-form-item label="销售负责人">
              <el-input
                v-model="form.salesOwner"
                placeholder="请选择销售单后自动带出"
                readonly
              />
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="退货原因">
              <el-input
                v-model="form.saleReturnReason"
                placeholder="请输入退货原因"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-card>

      <el-card shadow="never" class="card-section">
        <template #header>
          <div class="card-header detail-header">
            <span>退货明细</span>
            <div class="detail-actions">
              <el-button type="primary" @click="openGoodsDialog" :disabled="!form.salesOrderId">
                添加
              </el-button>
              <el-button
                type="danger"
                plain
                :disabled="!selectedDetailRows.length"
                @click="removeSelectedDetails"
              >
                移除
              </el-button>
            </div>
          </div>
        </template>

        <el-table
          ref="detailTableRef"
          :data="detailRows"
          border
          style="width: 100%"
          empty-text="请先选择销售单并通过'添加'按钮选择货品"
          @selection-change="handleDetailSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="productName" label="货品名称" min-width="140" />
          <el-table-column prop="productCode" label="货品编号" min-width="140" />
          <el-table-column prop="specificationModel" label="规格型号" min-width="120" />
          <el-table-column prop="unitName" label="单位" width="80" />
          <el-table-column label="可退数量" width="100" align="right">
            <template #default="{ row }">
              {{ Number(row.returnableQuantity ?? row.salesQuantity ?? 0) }}
            </template>
          </el-table-column>
          <el-table-column label="* 本次退货数量" width="140">
            <template #default="{ row }">
              <el-input-number
                v-model="row.returnQuantity"
                :precision="2"
                :min="0"
                :max="row.returnableQuantity || 999999"
                controls-position="right"
                placeholder="必填"
                @change="updateRowAmount(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="退货单价" width="140">
            <template #default="{ row }">
              <el-input-number
                v-model="row.unitPrice"
                :precision="4"
                :min="0"
                controls-position="right"
                @change="updateRowAmount(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="退货金额" width="140">
            <template #default="{ row }">
              ¥{{ row.amount?.toFixed(2) || '0.00' }}
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="150">
            <template #default="{ row }">
              <el-input
                v-model="row.remark"
                placeholder="请输入"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="80"
            fixed="right"
          >
            <template #default="scope">
              <el-button link type="danger" @click="removeDetail(scope.$index)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="detail-summary" v-if="detailRows.length">
          <span>退货种类：{{ detailSummary.kinds }}</span>
          <span>退货数量：{{ detailSummary.count }}</span>
          <span>退货金额：¥{{ detailSummary.amount.toFixed(2) }}</span>
        </div>
      </el-card>
    </el-form>

    <div class="fixed-footer">
      <div class="footer-actions">
        <el-button @click="handleBack">关闭</el-button>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="primary" :loading="saving" @click="handleSave">
          保存
        </el-button>
      </div>
    </div>

    <!-- 选择销售单 -->
    <el-dialog
      v-model="salesOrderDialog.visible"
      title="选择销售单"
      width="80%"
      :close-on-click-modal="false"
    >
      <el-form :model="salesOrderDialog.search" :inline="true" class="search-form">
        <el-form-item label="销售单号">
          <el-input
            v-model="salesOrderDialog.search.salesOrderNo"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
        <el-form-item label="单据状态">
          <el-select
            v-model="salesOrderDialog.search.salesOrderStatus"
            placeholder="请选择"
            clearable
            style="width: 150px"
          >
            <el-option label="全部（未出库/部分出库）" value="" />
            <el-option label="未出库" :value="3" />
            <el-option label="部分出库" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input
            v-model="salesOrderDialog.search.customerName"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadSalesOrders">查询</el-button>
          <el-button @click="resetSalesOrderDialog">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table
        v-loading="salesOrderDialog.loading"
        :data="salesOrderDialog.list"
        highlight-current-row
        @row-click="handleSalesOrderRowClick"
      >
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column label="选择" width="70">
          <template #default="{ row }">
            <el-radio v-model="selectedSalesOrderId" :label="row.salesOrderId">
              &nbsp;
            </el-radio>
          </template>
        </el-table-column>
        <el-table-column prop="salesOrderNo" label="销售单号" min-width="160" />
        <el-table-column label="单据状态" width="110">
          <template #default="{ row }">
            <el-tag
              :type="getSalesOrderStatusTag(row.salesOrderStatus)"
              size="small"
            >
              {{ getSalesOrderStatusText(row.salesOrderStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="salesOrderDate" label="销售日期" width="130">
          <template #default="{ row }">
            {{ formatDate(row.salesOrderDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="customerName" label="客户名称" min-width="160" />
        <el-table-column prop="salesDepartment" label="销售部门" width="140" />
        <el-table-column prop="salesOwner" label="销售负责人" width="100" />
        <el-table-column prop="salesOrderAmount" label="销售金额" width="140">
          <template #default="{ row }">
            ¥{{ Number(row.salesOrderAmount ?? 0).toFixed(2) }}
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <el-button @click="salesOrderDialog.visible = false">取消</el-button>
        <el-button
          type="primary"
          :disabled="!selectedSalesOrderRow"
          @click="confirmSalesOrderSelection"
        >
          确认
        </el-button>
      </template>
    </el-dialog>

    <!-- 添加退货明细 -->
    <el-dialog
      v-model="goodsDialog.visible"
      title="添加货品"
      width="80%"
      :close-on-click-modal="false"
    >
      <div class="goods-dialog-header" v-if="selectedSalesOrderRow">
        <div>销售单号：{{ selectedSalesOrderRow?.salesOrderNo }}</div>
        <div>销售日期：{{ formatDate(selectedSalesOrderRow?.salesOrderDate) }}</div>
      </div>

      <el-table
        v-loading="goodsDialog.loading"
        :data="goodsDialog.list"
        @selection-change="handleGoodsSelectionChange"
        height="420"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="productName" label="货品名称" min-width="140" />
        <el-table-column prop="productCode" label="货品编号" min-width="140" />
        <el-table-column prop="specificationModel" label="规格型号" min-width="120" />
        <el-table-column prop="unitName" label="单位" width="80" />
        <el-table-column prop="salesQuantity" label="销售数量" width="100" />
        <el-table-column prop="returnableQuantity" label="可退数量" width="90" />
        <el-table-column prop="unitPrice" label="销售单价" width="120">
          <template #default="{ row }">
            ¥{{ Number(row.unitPrice ?? 0).toFixed(4) }}
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <el-button @click="goodsDialog.visible = false">取消</el-button>
        <el-button
          type="primary"
          :disabled="!selectedGoodsRows.length"
          @click="confirmGoodsSelection"
        >
          确认添加
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { computed, nextTick, onMounted, reactive, ref, watch } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import moment from 'moment'
import myaxios from '@/http/MyAxios'

interface SaleReturnsForm {
  saleReturnsId?: string | number
  saleReturnsNo: string
  saleReturnsDate: string
  salesOrderId: string | number | null
  salesOrderNo: string
  salesOrderDate: string
  customerId?: string | number
  customerName?: string
  contactName?: string
  contactPhone?: string
  salesDepartment?: string
  salesOwner?: string
  saleReturnReason?: string
  remark?: string
  auditor?: string
  auditTime?: string
  saleReturnsStatus?: number
  saleReturnsStatusText?: string
}

interface SaleReturnDetailRow {
  uid: string
  salesOrderDetailId?: string | number
  productId?: string | number
  productCode?: string
  productName?: string
  specificationModel?: string
  unitName?: string
  unitId?: string | number
  salesQuantity?: number
  deliveredQuantity?: number
  returnableQuantity?: number
  returnQuantity: number
  unitPrice: number
  amount: number
  remark?: string
}

interface SalesOrderItem {
  salesOrderId: string | number
  salesOrderNo: string
  salesOrderStatus?: number
  salesOrderDate?: string
  customerId?: string | number
  customerName?: string
  salesDepartment?: string
  salesOwner?: string
  salesOrderAmount?: number
}

interface UnitItem {
  unitId: string | number
  unitName: string
}

const router = useRouter()
const route = useRoute()

const formRef = ref<FormInstance>()

const form = reactive<SaleReturnsForm>({
  saleReturnsNo: '',
  saleReturnsDate: moment().format('YYYY-MM-DD'),
  salesOrderId: null,
  salesOrderNo: '',
  salesOrderDate: '',
  customerName: '',
  contactName: '',
  contactPhone: '',
  salesDepartment: '',
  salesOwner: '',
  saleReturnReason: '',
  remark: '',
  auditor: '',
  auditTime: '',
})

const detailRows = ref<SaleReturnDetailRow[]>([])
const selectedDetailRows = ref<SaleReturnDetailRow[]>([])

const saving = ref(false)

const editingId = ref(route.query.saleReturnsId ? String(route.query.saleReturnsId) : '')

const formRules: FormRules = {
  saleReturnsNo: [{ required: true, message: '销售退货单号不能为空', trigger: 'blur' }],
  saleReturnsDate: [{ required: true, message: '请选择退货日期', trigger: 'change' }],
  salesOrderNo: [{ required: true, message: '请选择销售单号', trigger: 'change' }],
  customerName: [{ required: true, message: '请选择客户', trigger: 'change' }],
}

const detailSummary = reactive({
  kinds: 0,
  count: 0,
  amount: 0,
})

const unitOptions = ref<UnitItem[]>([])

// 销售单选择对话框
const salesOrderDialog = reactive({
  visible: false,
  loading: false,
  list: [] as SalesOrderItem[],
  search: {
    salesOrderNo: '',
    salesOrderStatus: '',
    customerName: '',
  },
})

const selectedSalesOrderId = ref<string | number | null>(null)
const selectedSalesOrderRow = ref<SalesOrderItem | null>(null)

// 货品选择对话框
const goodsDialog = reactive({
  visible: false,
  loading: false,
  list: [] as SaleReturnDetailRow[],
})

const selectedGoodsRows = ref<SaleReturnDetailRow[]>([])

const SALES_ORDER_STATUS_OPTIONS = [
  { value: 0, label: '草稿', tagType: 'info' },
  { value: 1, label: '待审核', tagType: 'warning' },
  { value: 2, label: '驳回', tagType: 'danger' },
  { value: 3, label: '未出库', tagType: 'info' },
  { value: 4, label: '部分出库', tagType: 'warning' },
  { value: 5, label: '已出库', tagType: 'success' },
  { value: 6, label: '已完成', tagType: 'success' },
  { value: 7, label: '已关闭', tagType: 'danger' },
]

const formatDate = (value?: string | null) => {
  if (!value) return ''
  return moment(value).format('YYYY-MM-DD')
}

const getSalesOrderStatusText = (status: number | string | undefined): string => {
  if (status === undefined || status === null) return '未知'
  const statusNum = Number(status)
  const option = SALES_ORDER_STATUS_OPTIONS.find((opt) => opt.value === statusNum)
  return option?.label || '未知'
}

const getSalesOrderStatusTag = (status: number | string | undefined): string => {
  if (status === undefined || status === null) return 'info'
  const statusNum = Number(status)
  const option = SALES_ORDER_STATUS_OPTIONS.find((opt) => opt.value === statusNum)
  return option?.tagType || 'info'
}

const updateSummary = () => {
  const rows = detailRows.value
  detailSummary.kinds = rows.length
  detailSummary.count = rows.reduce((sum, row) => sum + Number(row.returnQuantity || 0), 0)
  detailSummary.amount = rows.reduce((sum, row) => sum + Number(row.amount || 0), 0)
}

const updateRowAmount = (row: SaleReturnDetailRow) => {
  const qty = Number(row.returnQuantity || 0)
  const price = Number(row.unitPrice || 0)
  row.amount = Number((qty * price).toFixed(2))
  updateSummary()
}

watch(
  () => detailRows.value.length,
  () => updateSummary(),
)

const handleDetailSelectionChange = (rows: SaleReturnDetailRow[]) => {
  selectedDetailRows.value = rows
}

const removeSelectedDetails = () => {
  if (!selectedDetailRows.value.length) return
  detailRows.value = detailRows.value.filter(
    (item) => !selectedDetailRows.value.includes(item),
  )
  selectedDetailRows.value = []
  updateSummary()
}

const removeDetail = (index: number) => {
  detailRows.value.splice(index, 1)
  updateSummary()
}

// 加载单位列表
const loadUnitOptions = async () => {
  try {
    const res = await myaxios.get('/api/Unit/GetUnitList')
    if (res?.data?.code === 200) {
      unitOptions.value = (res.data.data || []).map((unit: any) => ({
        unitId: unit.unitId || unit.id,
        unitName: unit.unitName || unit.name || '',
      }))
    }
  } catch (error) {
    console.warn('加载单位列表失败:', error)
    unitOptions.value = []
  }
}

// 根据单位名称获取单位ID
const getUnitIdByName = (name?: string | number | null): number | null => {
  if (!name && name !== 0) return null
  const normalized = String(name)
  const hit = unitOptions.value.find(
    (unit) => unit.unitName === normalized || String(unit.unitId) === normalized,
  )
  if (hit) return Number(hit.unitId)
  return null
}

// 销售单相关
const openSalesOrderDialog = () => {
  salesOrderDialog.visible = true
  if (!salesOrderDialog.list.length) {
    loadSalesOrders()
  }
}

const resetSalesOrderDialog = () => {
  salesOrderDialog.search.salesOrderNo = ''
  salesOrderDialog.search.salesOrderStatus = ''
  salesOrderDialog.search.customerName = ''
  loadSalesOrders()
}

const loadSalesOrders = async () => {
  salesOrderDialog.loading = true
  try {
    // 如果用户选择了特定状态，只查询该状态
    if (salesOrderDialog.search.salesOrderStatus !== '' && salesOrderDialog.search.salesOrderStatus !== null && salesOrderDialog.search.salesOrderStatus !== undefined) {
      const params: Record<string, any> = {
        salesOrderNo: salesOrderDialog.search.salesOrderNo,
        customerName: salesOrderDialog.search.customerName,
        salesOrderStatus: salesOrderDialog.search.salesOrderStatus,
        pageindex: 1,
        pagesize: 100,
      }
      
      const res = await myaxios.get('/api/SalesOrder/GetSalesOrders', { params })
      if (res?.data?.code === 200 || res?.data?.success) {
        const section = res.data?.data ?? res.data
        const rawList = Array.isArray(section) ? section : (section?.data || section?.list || [])
        salesOrderDialog.list = rawList.map((item: any) => ({
          salesOrderId: item.salesOrderId || item.id || '',
          salesOrderNo: item.salesOrderNo || item.orderNo || '',
          salesOrderStatus: item.salesOrderStatus ?? item.status ?? 0,
          salesOrderDate: item.salesOrderDate || item.orderDate || '',
          customerId: item.customerId || '',
          customerName: item.customerName || item.customer || '',
          salesDepartment: item.organizationName || item.salesDepartment || '',
          salesOwner: item.userName || item.salesOwner || '',
          salesOrderAmount: Number(item.salesOrderAmount ?? item.amount ?? 0),
        }))
      }
    } else {
      // 默认情况：分别查询未出库（3）和部分出库（4）状态
      const allResults: any[] = []
      
      try {
        const params3: Record<string, any> = {
          salesOrderNo: salesOrderDialog.search.salesOrderNo,
          customerName: salesOrderDialog.search.customerName,
          salesOrderStatus: 3,
          pageindex: 1,
          pagesize: 100,
        }
        const res3 = await myaxios.get('/api/SalesOrder/GetSalesOrders', { params: params3 })
        if (res3?.data?.code === 200 || res3?.data?.success) {
          const section3 = res3.data?.data ?? res3.data
          const rawList3 = Array.isArray(section3) ? section3 : (section3?.data || section3?.list || [])
          allResults.push(...rawList3)
        }
      } catch (error3) {
        console.warn('查询未出库状态失败:', error3)
      }
      
      try {
        const params4: Record<string, any> = {
          salesOrderNo: salesOrderDialog.search.salesOrderNo,
          customerName: salesOrderDialog.search.customerName,
          salesOrderStatus: 4,
          pageindex: 1,
          pagesize: 100,
        }
        const res4 = await myaxios.get('/api/SalesOrder/GetSalesOrders', { params: params4 })
        if (res4?.data?.code === 200 || res4?.data?.success) {
          const section4 = res4.data?.data ?? res4.data
          const rawList4 = Array.isArray(section4) ? section4 : (section4?.data || section4?.list || [])
          allResults.push(...rawList4)
        }
      } catch (error4) {
        console.warn('查询部分出库状态失败:', error4)
      }
      
      // 映射数据并去重
      const uniqueMap = new Map()
      salesOrderDialog.list = allResults
        .map((item: any) => ({
          salesOrderId: item.salesOrderId || item.id || '',
          salesOrderNo: item.salesOrderNo || item.orderNo || '',
          salesOrderStatus: item.salesOrderStatus ?? item.status ?? 0,
          salesOrderDate: item.salesOrderDate || item.orderDate || '',
          customerId: item.customerId || '',
          customerName: item.customerName || item.customer || '',
          salesDepartment: item.organizationName || item.salesDepartment || '',
          salesOwner: item.userName || item.salesOwner || '',
          salesOrderAmount: Number(item.salesOrderAmount ?? item.amount ?? 0),
        }))
        .filter((item) => {
          const key = item.salesOrderId || item.salesOrderNo
          if (key && !uniqueMap.has(key)) {
            uniqueMap.set(key, true)
            return true
          }
          return false
        })
    }
  } catch (error) {
    console.error('获取销售单失败', error)
    ElMessage.error('获取销售单列表失败')
  } finally {
    salesOrderDialog.loading = false
  }
}

const handleSalesOrderRowClick = (row: SalesOrderItem) => {
  selectedSalesOrderId.value = row.salesOrderId
  selectedSalesOrderRow.value = row
}

const applySalesOrderToForm = (row: SalesOrderItem) => {
  selectedSalesOrderRow.value = row
  form.salesOrderId = row.salesOrderId
  form.salesOrderNo = row.salesOrderNo
  form.salesOrderDate = formatDate(row.salesOrderDate) || ''
  form.customerId = row.customerId
  form.customerName = row.customerName || ''
  // 需要从销售单详情获取更多信息
  loadSalesOrderDetails(row.salesOrderId)
}

const loadSalesOrderDetails = async (salesOrderId: string | number) => {
  try {
    const res = await myaxios.get('/api/SalesOrder/GetSalesOrderDetail', {
      params: { salesOrderId },
    })
    if (res?.data?.code === 200) {
      const data = res.data.data || {}
      form.contactName = data.contactName || data.salesContact || ''
      form.contactPhone = data.contactPhone || data.salesContactPhone || ''
      form.salesDepartment = data.organizationName || data.salesDepartment || ''
      form.salesOwner = data.userName || data.salesOwner || ''
    }
  } catch (error) {
    console.warn('获取销售单详情失败:', error)
  }
}

const confirmSalesOrderSelection = () => {
  if (!selectedSalesOrderRow.value) {
    ElMessage.warning('请选择销售单')
    return
  }
  applySalesOrderToForm(selectedSalesOrderRow.value)
  salesOrderDialog.visible = false
  // 加载销售单明细
  loadSalesOrderGoods(selectedSalesOrderRow.value.salesOrderId)
}

// 加载销售单货品明细
// 从销售订单明细获取单价和可退数量并更新到明细行
const loadSalesOrderGoodsForPrice = async (salesOrderId: string | number, detailRows: SaleReturnDetailRow[]) => {
  try {
    const res = await myaxios.get('/api/SalesOrder/GetSalesOrderDetails', {
      params: { salesOrderId },
    })
    if (res?.data?.code === 200 || res?.data?.success) {
      const section = res.data?.data ?? res.data
      const rawList = Array.isArray(section) ? section : (section?.data || section?.list || [])
      
      // 创建销售订单明细的映射，用于快速查找
      const salesOrderDetailMap = new Map()
      rawList.forEach((item: any) => {
        const detailId = item.salesOrderDetailId || item.id
        const productId = item.productId
        if (detailId) {
          salesOrderDetailMap.set(detailId, item)
        }
        if (productId) {
          salesOrderDetailMap.set(`product_${productId}`, item)
        }
      })
      
      // 更新明细行的单价和可退数量
      let updatedPriceCount = 0
      let updatedQtyCount = 0
      detailRows.forEach((detailRow) => {
        // 尝试通过销售订单明细ID查找
        let salesOrderDetail: any = null
        if (detailRow.salesOrderDetailId) {
          salesOrderDetail = salesOrderDetailMap.get(detailRow.salesOrderDetailId)
        }
        // 如果找不到，尝试通过产品ID查找
        if (!salesOrderDetail && detailRow.productId) {
          salesOrderDetail = salesOrderDetailMap.get(`product_${detailRow.productId}`)
        }
        
        if (salesOrderDetail) {
          // 更新单价
          if (detailRow.unitPrice === 0 && detailRow.returnQuantity > 0) {
            // 解析单价
            const priceFields = ['unitPrice', 'salesPrice', 'salePrice', 'salesUnitPrice', 'price']
            for (const field of priceFields) {
              const value = salesOrderDetail[field]
              if (value !== undefined && value !== null && value !== '') {
                const num = Number(value)
                if (!Number.isNaN(num) && num > 0) {
                  detailRow.unitPrice = num
                  // 重新计算金额
                  detailRow.amount = Number((detailRow.returnQuantity * num).toFixed(2))
                  updatedPriceCount++
                  console.log(`从销售订单明细更新单价: ${detailRow.productName} = ${num}`)
                  break
                }
              }
            }
            
            // 如果还是找不到，尝试从金额和数量计算
            if (detailRow.unitPrice === 0) {
              const salesQty = Number(salesOrderDetail.salesQuantity || salesOrderDetail.quantity || 0)
              const salesAmount = Number(salesOrderDetail.amount || salesOrderDetail.salesAmount || 0)
              if (salesQty > 0 && salesAmount > 0) {
                detailRow.unitPrice = Number((salesAmount / salesQty).toFixed(4))
                detailRow.amount = Number((detailRow.returnQuantity * detailRow.unitPrice).toFixed(2))
                updatedPriceCount++
                console.log(`从销售订单明细计算单价: ${detailRow.productName} = ${detailRow.unitPrice}`)
              }
            }
          }
          
          // 更新可退数量
          if (detailRow.returnableQuantity === 0 || !detailRow.returnableQuantity) {
            const salesQty = Number(salesOrderDetail.salesQuantity || salesOrderDetail.quantity || 0)
            const deliveredQty = Number(
              salesOrderDetail.deliveredQuantity || 
              salesOrderDetail.deliveredQty || 
              salesOrderDetail.outboundQuantity || 
              salesOrderDetail.outboundQty || 
              0
            )
            const returnedQty = Number(
              salesOrderDetail.returnedQuantity || 
              salesOrderDetail.returnedQty || 
              salesOrderDetail.accumulatedReturnQuantity || 
              0
            )
            
            if (salesQty > 0) {
              const calculatedReturnableQty = Math.max(0, salesQty - deliveredQty - returnedQty)
              detailRow.returnableQuantity = calculatedReturnableQty
              detailRow.salesQuantity = salesQty
              detailRow.deliveredQuantity = deliveredQty
              updatedQtyCount++
              console.log(`从销售订单明细更新可退数量: ${detailRow.productName} = ${calculatedReturnableQty} (销售: ${salesQty}, 已交付: ${deliveredQty}, 已退货: ${returnedQty})`)
            }
          }
        }
      })
      
      if (updatedPriceCount > 0 || updatedQtyCount > 0) {
        console.log(`成功更新了 ${updatedPriceCount} 个明细项的单价，${updatedQtyCount} 个明细项的可退数量`)
        updateSummary()
      }
    }
  } catch (error) {
    console.warn('从销售订单获取单价和可退数量失败:', error)
  }
}

const loadSalesOrderGoods = async (salesOrderId: string | number) => {
  goodsDialog.loading = true
  try {
    const res = await myaxios.get('/api/SalesOrder/GetSalesOrderDetails', {
      params: { salesOrderId },
    })
    if (res?.data?.code === 200 || res?.data?.success) {
      const section = res.data?.data ?? res.data
      const rawList = Array.isArray(section) ? section : (section?.data || section?.list || [])
      
      goodsDialog.list = rawList.map((item: any) => {
        const salesQty = Number(item.salesQuantity || item.quantity || 0)
        const deliveredQty = Number(item.deliveredQuantity || item.deliveredQty || 0)
        const returnableQty = Math.max(0, salesQty - deliveredQty)
        
        // 解析单价
        const priceFields = ['unitPrice', 'salesPrice', 'salePrice', 'salesUnitPrice', 'price', 'amount']
        let unitPrice = 0
        for (const field of priceFields) {
          const value = item[field]
          if (value !== undefined && value !== null && value !== '') {
            const num = Number(value)
            if (!Number.isNaN(num) && num > 0) {
              unitPrice = num
              break
            }
          }
        }
        
        // 如果单价字段不存在，尝试从金额和数量计算
        if (unitPrice === 0 && salesQty > 0) {
          const amount = Number(item.amount || item.salesAmount || 0)
          if (amount > 0) {
            unitPrice = Number((amount / salesQty).toFixed(4))
          }
        }
        
        return {
          uid: `${item.salesOrderDetailId || item.productId || Date.now()}`,
          salesOrderDetailId: item.salesOrderDetailId || item.id,
          productId: item.productId,
          productCode: item.productCode || '',
          productName: item.productName || '',
          specificationModel: item.specificationModel || item.specification || '',
          unitName: item.unitName || item.unit || '',
          unitId: item.unitId || item.unitID,
          salesQuantity: salesQty,
          deliveredQuantity: deliveredQty,
          returnableQuantity: returnableQty,
          returnQuantity: returnableQty,
          unitPrice: unitPrice,
          amount: Number((returnableQty * unitPrice).toFixed(2)),
          remark: '',
        }
      })
    } else {
      goodsDialog.list = []
      ElMessage.error(res?.data?.message || '获取销售明细失败')
    }
  } catch (error) {
    console.error('获取销售明细失败', error)
    goodsDialog.list = []
    ElMessage.error('获取销售明细失败')
  } finally {
    goodsDialog.loading = false
  }
}

const openGoodsDialog = () => {
  if (!form.salesOrderId) {
    ElMessage.warning('请先选择销售单')
    return
  }
  goodsDialog.visible = true
  if (!goodsDialog.list.length) {
    loadSalesOrderGoods(form.salesOrderId)
  }
}

const handleGoodsSelectionChange = (rows: SaleReturnDetailRow[]) => {
  selectedGoodsRows.value = rows
}

const confirmGoodsSelection = () => {
  if (!selectedGoodsRows.value.length) {
    ElMessage.warning('请选择需要添加的货品')
    return
  }
  
  selectedGoodsRows.value.forEach((item) => {
    const exists = detailRows.value.find(
      (row) => row.salesOrderDetailId === item.salesOrderDetailId || row.productId === item.productId,
    )
    if (exists) {
      // 更新已存在的项
      exists.returnableQuantity = item.returnableQuantity
      if (item.unitPrice && item.unitPrice > 0) {
        exists.unitPrice = item.unitPrice
        updateRowAmount(exists)
      }
    } else {
      // 添加新项
      const returnQty = item.returnableQuantity ?? item.salesQuantity ?? 0
      const finalUnitPrice = item.unitPrice && item.unitPrice > 0 ? item.unitPrice : 0
      
      detailRows.value.push({
        uid: `${item.salesOrderDetailId || item.productId || Date.now()}`,
        salesOrderDetailId: item.salesOrderDetailId,
        productId: item.productId,
        productName: item.productName,
        productCode: item.productCode,
        specificationModel: item.specificationModel,
        unitName: item.unitName,
        unitId: item.unitId,
        salesQuantity: item.salesQuantity,
        deliveredQuantity: item.deliveredQuantity,
        returnableQuantity: item.returnableQuantity ?? item.salesQuantity,
        returnQuantity: returnQty,
        unitPrice: finalUnitPrice,
        amount: Number((finalUnitPrice * returnQty).toFixed(2)),
        remark: '',
      })
    }
  })
  
  goodsDialog.visible = false
  updateSummary()
}

const validateDetails = () => {
  if (!detailRows.value || detailRows.value.length === 0) {
    ElMessage.warning('退货明细不能为空，请添加退货明细')
    return false
  }
  
  const validRows = detailRows.value.filter((row) => {
    const hasProductId = !!row.productId
    const returnQty = Number(row.returnQuantity || 0)
    const unitPrice = Number(row.unitPrice || 0)
    return hasProductId && returnQty > 0 && unitPrice > 0
  })
  
  if (validRows.length === 0) {
    ElMessage.warning('退货明细不能为空，请填写完整的退货数量和单价（必须大于0）')
    return false
  }
  
  return true
}

const buildSavePayload = () => {
  const details = detailRows.value
    .filter((row) => {
      const hasProductId = !!row.productId
      const returnQty = Number(row.returnQuantity || 0)
      const unitPrice = Number(row.unitPrice || 0)
      return hasProductId && returnQty > 0 && unitPrice > 0
    })
    .map((row) => {
      const returnQty = Number(row.returnQuantity || 0)
      const unitPrice = Number(row.unitPrice || 0)
      const amount = Number(row.amount || 0) || Number((returnQty * unitPrice).toFixed(2))
      
      const unitNameValue = row.unitName || ''
      let unitIdValue = getUnitIdByName(unitNameValue || row.unitId || null)
      
      if (unitIdValue === null) {
        if (row.unitId) {
          unitIdValue = Number(row.unitId)
        } else {
          console.warn(`无法找到单位ID，单位名称: ${unitNameValue}，货品: ${row.productName}`)
          unitIdValue = 0
        }
      }
      
      return {
        salesOrderDetailId: row.salesOrderDetailId || null,
        productId: Number(row.productId) || 0,
        productCode: row.productCode || '',
        productName: row.productName || '',
        specificationModel: row.specificationModel || '',
        unitName: unitIdValue,
        unitDisplayName: String(unitNameValue),
        unitId: unitIdValue,
        quantity: returnQty,
        returnQuantity: returnQty,
        unitPrice: unitPrice,
        returnUnitPrice: unitPrice,
        amount: amount,
        returnAmount: amount,
        remark: row.remark || '',
      }
    })
  
  if (!details || details.length === 0) {
    throw new Error('退货明细不能为空')
  }
  
  return {
    ...form,
    saleReturnsId: form.saleReturnsId,
    saleReturnsQuantity: detailSummary.count,
    saleReturnsAmount: detailSummary.amount,
    saleReturnsDetails: details,
    goodsDetails: details,
    details: details,
  }
}

const handleSave = async () => {
  if (saving.value) return
  if (!editingId.value) {
    ElMessage.error('缺少销售退货单ID，无法保存')
    return
  }
  await formRef.value?.validate()
  if (!validateDetails()) return
  saving.value = true
  try {
    const payload = buildSavePayload()
    const res = await myaxios.put('/api/SaleReturns/UpdateSaleReturns', payload)
    if (res?.data?.code === 200) {
      ElMessage.success(res?.data?.message || '保存成功')
      router.push('/getsalereturn')
    } else {
      ElMessage.error(res?.data?.message || '保存失败')
    }
  } catch (error: any) {
    console.error('保存销售退货失败:', error)
    ElMessage.error(error?.response?.data?.message || '保存失败，请稍后重试')
  } finally {
    saving.value = false
  }
}

const handleReset = () => {
  if (editingId.value) {
    loadSaleReturnsDetail(editingId.value)
  } else {
    formRef.value?.resetFields()
    form.saleReturnsDate = moment().format('YYYY-MM-DD')
    form.salesOrderId = null
    form.salesOrderNo = ''
    form.salesOrderDate = ''
    form.customerId = ''
    form.customerName = ''
    form.contactName = ''
    form.contactPhone = ''
    form.salesDepartment = ''
    form.salesOwner = ''
    detailRows.value = []
    selectedSalesOrderRow.value = null
    updateSummary()
  }
}

const handleBack = () => {
  router.push('/getsalereturn')
}

const applySaleReturnsDetail = (data: any) => {
  console.log('applySaleReturnsDetail 接收到的数据:', data)
  form.saleReturnsId = data.saleReturnsId || data.SaleReturnsId || editingId.value
  form.saleReturnsNo = data.saleReturnsNo || data.SaleReturnsNo || ''
  form.saleReturnsDate = formatDate(data.saleReturnsDate || data.SaleReturnsDate) || form.saleReturnsDate
  form.salesOrderId = data.salesOrderId || data.SalesOrderId || null
  form.salesOrderNo = data.salesOrderNo || data.SaleOrderNo || data.orderNo || ''
  form.salesOrderDate = formatDate(data.salesOrderDate || data.SaleOrderDate) || ''
  form.customerId = data.customerId || data.CustomerId || ''
  form.customerName = data.customerName || data.CustomerName || data.customer || ''
  form.contactName = data.contactName || data.saleReturnsContact || data.contact || ''
  form.contactPhone = data.contactPhone || data.saleReturnsContactPhone || data.contactMethod || ''
  form.salesDepartment = data.salesDepartment || data.saleReturnsDepartment || data.organizationName || ''
  form.salesOwner = data.salesOwner || data.saleReturnsUser || data.userName || ''
  form.saleReturnReason = data.saleReturnReason || data.reason || ''
  form.remark = data.remark || data.saleReturnsRemark || ''
  form.auditor = data.auditor || ''
  form.auditTime = data.auditTime || ''
  form.saleReturnsStatus = data.saleReturnsStatus || data.SaleReturnsStatus
  form.saleReturnsStatusText = data.saleReturnsStatusText || data.statusText || ''

  // 尝试多种方式获取退货明细数据
  let details: any[] = []
  
  const detailCandidates = [
    data.saleReturnsDetails,
    data.goodsDetails,
    data.details,
    data.SaleReturnsDetails,
    data.detailList,
    data.DetailList,
    data.saleReturnsDetailList,
    data.returnDetails,
    data.items,
    data.list,
    data.records,
  ]
  
  for (const candidate of detailCandidates) {
    if (candidate) {
      if (Array.isArray(candidate) && candidate.length > 0) {
        details = candidate
        console.log('找到退货明细数据，数量:', details.length)
        break
      }
      if (typeof candidate === 'string') {
        try {
          const parsed = JSON.parse(candidate)
          if (Array.isArray(parsed) && parsed.length > 0) {
            details = parsed
            console.log('从字符串解析到退货明细数据，数量:', details.length)
            break
          }
        } catch (e) {
          // 忽略解析错误
        }
      }
    }
  }
  
  if (!details.length) {
    const nestedCandidates = [
      data.data?.saleReturnsDetails,
      data.data?.goodsDetails,
      data.data?.details,
      data.data?.list,
      data.data?.records,
    ]
    for (const candidate of nestedCandidates) {
      if (Array.isArray(candidate) && candidate.length > 0) {
        details = candidate
        console.log('从嵌套结构找到退货明细数据，数量:', details.length)
        break
      }
    }
  }

  if (!Array.isArray(details)) {
    console.warn('退货明细数据不是数组:', details)
    details = []
  }

  // 销售退货明细中可能包含单价的字段名列表（按优先级排序）
  const SALE_RETURNS_PRICE_FIELDS = [
    'unitPrice',
    'returnUnitPrice',
    'saleReturnsUnitPrice',
    'salesPrice',
    'salePrice',
    'salesUnitPrice',
    'productSalePrice',
    'productSaleMoney',
    'productOutMoney',
    'outPrice',
    'price',
    'productPrice',
  ]

  // 从销售退货明细项中解析单价
  const resolveSaleReturnsDetailPrice = (item: any, returnQty: number, amount: number): number => {
    // 优先尝试直接字段
    for (const key of SALE_RETURNS_PRICE_FIELDS) {
      const value = item?.[key]
      if (value !== undefined && value !== null && value !== '') {
        const num = Number(value)
        if (!Number.isNaN(num) && Number.isFinite(num) && num > 0) {
          return num
        }
      }
    }
    
    // 如果单价字段不存在或为0，尝试从金额和数量计算
    if (returnQty > 0 && amount > 0) {
      const calculatedPrice = Number((amount / returnQty).toFixed(4))
      if (calculatedPrice > 0) {
        return calculatedPrice
      }
    }
    
    // 如果都找不到，返回0（但会在控制台警告）
    return 0
  }

  // 映射明细数据
  const mappedDetails = details.map((item: any, index: number) => {
    const returnQty = Number(item.returnQuantity || item.quantity || item.saleReturnsQuantity || 0)
    const amount = Number(item.amount || item.returnAmount || item.saleReturnsAmount || 0)
    
    // 使用解析函数获取单价
    let unitPrice = resolveSaleReturnsDetailPrice(item, returnQty, amount)
    
    // 如果单价为0但金额和数量都有值，从金额和数量计算单价
    if (unitPrice === 0 && returnQty > 0 && amount > 0) {
      unitPrice = Number((amount / returnQty).toFixed(4))
      console.log(`从金额和数量计算单价: ${amount} / ${returnQty} = ${unitPrice}`, item)
    }
    
    // 如果单价仍然为0，尝试从销售订单明细获取原始单价
    if (unitPrice === 0 && item.salesOrderDetailId) {
      // 这里可以尝试从销售订单明细获取，但需要先加载销售订单明细
      // 暂时先记录警告
      console.warn(`明细项 ${index + 1} (${item.productName || item.productCode || '未知'}) 的单价为0，尝试从销售订单获取`, item)
    }
    
    // 如果金额为0但数量和单价都有值，重新计算金额
    const finalAmount = amount > 0 ? amount : (returnQty > 0 && unitPrice > 0 ? Number((returnQty * unitPrice).toFixed(2)) : 0)
    
    // 获取销售数量和已交付数量（尝试多个字段名）
    const salesQty = Number(
      item.salesQuantity || 
      item.quantity || 
      item.saleQuantity || 
      item.salesQty || 
      item.saleQty || 
      0
    )
    const deliveredQty = Number(
      item.deliveredQuantity || 
      item.deliveredQty || 
      item.outboundQuantity || 
      item.outboundQty || 
      item.outQuantity || 
      item.outQty || 
      0
    )
    const returnedQty = Number(
      item.returnedQuantity || 
      item.returnedQty || 
      item.accumulatedReturnQuantity || 
      0
    )
    
    // 计算可退数量：销售数量 - 已交付数量 - 已退货数量
    // 优先使用后端返回的可退数量，如果没有则计算
    let returnableQty = Number(item.returnableQuantity || item.returnableQty || 0)
    if (returnableQty === 0 && salesQty > 0) {
      // 如果后端没有返回可退数量，从销售数量和已交付数量计算
      returnableQty = Math.max(0, salesQty - deliveredQty - returnedQty)
    }
    
    return {
      uid: `${item.saleReturnsDetailId || item.id || item.productId || `detail-${index}-${Date.now()}`}`,
      salesOrderDetailId: item.salesOrderDetailId || item.salesOrderDetailID,
      productId: item.productId || item.ProductId || item.productID,
      productCode: item.productCode || item.ProductCode || item.code || '',
      productName: item.productName || item.ProductName || item.name || '',
      specificationModel: item.specificationModel || item.specification || item.Specification || '',
      unitName: item.unitName || item.unit || item.UnitName || '',
      unitId: item.unitId || item.unitID || item.UnitId,
      salesQuantity: salesQty,
      deliveredQuantity: deliveredQty,
      returnableQuantity: returnableQty,
      returnQuantity: returnQty,
      unitPrice: unitPrice,
      amount: finalAmount,
      remark: item.remark || item.Remark || '',
    }
  })
  
  // 检查是否有单价为0或可退数量为0的项，如果有，尝试从销售订单明细获取
  const zeroPriceItems = mappedDetails.filter((item) => item.unitPrice === 0 && item.returnQuantity > 0)
  const zeroReturnableQtyItems = mappedDetails.filter((item) => (item.returnableQuantity === 0 || !item.returnableQuantity) && item.salesQuantity > 0)
  
  if ((zeroPriceItems.length > 0 || zeroReturnableQtyItems.length > 0) && form.salesOrderId) {
    if (zeroPriceItems.length > 0) {
      console.warn(`有 ${zeroPriceItems.length} 个明细项的单价为0，尝试从销售订单获取原始单价`, zeroPriceItems)
    }
    if (zeroReturnableQtyItems.length > 0) {
      console.warn(`有 ${zeroReturnableQtyItems.length} 个明细项的可退数量为0或缺失，尝试从销售订单获取`, zeroReturnableQtyItems)
    }
    // 异步加载销售订单明细并更新单价和可退数量
    loadSalesOrderGoodsForPrice(form.salesOrderId, mappedDetails)
  }
  
  console.log('映射后的退货明细数量:', mappedDetails.length)
  detailRows.value = mappedDetails
  updateSummary()
}

const loadSaleReturnsDetail = async (id: string) => {
  try {
    const res = await myaxios.get('/api/SaleReturns/GetSaleReturnsDetail', {
      params: { saleReturnsId: id },
    })
    console.log('获取销售退货单详情完整响应:', res)
    
    if (res?.data?.code === 200) {
      const detailData = res.data.data || res.data || {}
      console.log('准备应用的数据:', detailData)
      applySaleReturnsDetail(detailData)
    } else {
      ElMessage.error(res?.data?.message || '获取销售退货单详情失败')
    }
  } catch (error) {
    console.error('获取销售退货单详情失败:', error)
    ElMessage.error('获取销售退货单详情失败，请稍后重试')
  }
}

onMounted(async () => {
  await loadUnitOptions()
  if (!editingId.value) {
    ElMessage.error('缺少销售退货单ID')
    router.push('/getsalereturn')
    return
  }
  await loadSaleReturnsDetail(editingId.value)
})
</script>

<style scoped>
.sale-return-update-page {
  padding: 16px 16px 96px;
  background: #f5f7fa;
}

.page-header {
  margin-bottom: 16px;
}

.card-section {
  margin-bottom: 16px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 12px;
  font-weight: 600;
  font-size: 16px;
}

.detail-header {
  justify-content: space-between;
}

.detail-actions {
  display: flex;
  gap: 8px;
}

.readonly-input :deep(.el-input__inner) {
  cursor: pointer;
}

.detail-summary {
  margin-top: 12px;
  padding: 8px 12px;
  background: #f9fafc;
  border: 1px dashed #e4e7ed;
  border-radius: 4px;
  color: #606266;
  display: flex;
  gap: 24px;
}

.fixed-footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.08);
  padding: 12px 24px;
  display: flex;
  justify-content: flex-end;
  z-index: 20;
}

.footer-actions {
  display: flex;
  gap: 12px;
}

.search-form {
  margin-bottom: 12px;
}

.goods-dialog-header {
  display: flex;
  gap: 24px;
  margin-bottom: 12px;
  font-size: 13px;
  color: #606266;
}
</style>

